package utils

import (
	"errors"
	"exchangeapp/config"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
	"time"
)

func HashPassword(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(hash), err
}

func GenerateJWT(username string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": username,
		"exp":      time.Now().Add(time.Minute * config.AppConfig.Jwt.Exp).Unix(),
	})
	signedToken, err := token.SignedString([]byte(config.AppConfig.Jwt.Secret))
	return config.AppConfig.Jwt.Prefix + signedToken, err
}

func MatchPassword(hash string, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

func ParseToken(tokenString string) (string, error) {
	if len(tokenString) > 7 && tokenString[:7] == config.AppConfig.Jwt.Prefix {
		tokenString = tokenString[7:]
	}
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("未知的签名方法")
		}
		return []byte(config.AppConfig.Jwt.Secret), nil
	})
	if err != nil {
		return "", err
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		username, ok := claims["username"].(string)
		if !ok {
			return "", errors.New("不合法的claim")
		}
		exp, ok := claims["exp"].(float64)
		if !ok {
			return "", errors.New("不合法的claim")
		}
		expirationTime := time.Unix(int64(exp), 0)
		if time.Now().After(expirationTime) {
			return "", errors.New("登录已过期，请重新登录！")
		}
		return username, nil
	}
	return "", errors.New("不合法的token")
}
